<template>

  <div class="main-app" style="margin-top: 20px;">
    <el-row style="margin-left: 20%; " :gutter="50">

      <el-col :span="8">
        <el-divider content-position="left">后台管理系统</el-divider>
        <el-tree ref="tree" :data="AllMenuIdList" show-checkbox node-key="id" :default-expanded-keys="[]"
                 :default-checked-keys="checkedMenuIdList" :props="defaultProps" @check-change="handleCheckChange"
        />

      </el-col>

      <el-col :span="8">
        <el-divider content-position="left">小程序</el-divider>
        <el-tree :data="AllMenuIdList_Mp" show-checkbox node-key="id" :default-expanded-keys="[]"
                 :default-checked-keys="[]" :props="defaultProps" @check-change="handleCheckChange"
        />

      </el-col>

    </el-row>
    <el-row style="margin-top: 100px; text-align: center">
      <el-form :inline="true" class="form-inline">
        <el-form-item>
          <el-button type="primary" @click="save">保存</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="clearAll">清空所有</el-button>
        </el-form-item>
      </el-form>
    </el-row>

  </div>
</template>

<script>
import {
  GetTreeMenusByRoleTwoAsync,
  UpdateAuthorityAsync
} from '../../../api/role.js';
export default {
  data() {
    return {
      id: "",
      checkedMenuIdList: [],
      selectedMenuIdList: [],
      AllMenuIdList: [],
      AllMenuIdList_Mp: [],

      number: 0,
      weight: 0,
      form: {
        name: "",
        disabled: 0,
        sort: 0
      },

      defaultProps: {
        children: 'children',
        label: 'label',
        disabled: 'disabled',
      },

      rules: {
        name: [{
          required: true,
          message: "请输入角色名称",
          trigger: "blur"
        }],
        sort: [{
          required: true,
          message: "请输入排序号",
          trigger: "blur"
        }],

      },
    };
  },

  async created() {
    const {
      id,
    } = this.$route.params;
    this.id = id;
    await this.init();
  },

  methods: {
    clearAll() {
      // console.log(this.$refs.tree.getCheckedNodes());
      // console.log(this.$refs.tree.getCheckedKeys());
      this.selectedMenuIdList = [];
      this.$refs.tree.setCheckedKeys([]);
    },
    handleCheckChange(data, checked, indeterminate) {
      if (!checked && !indeterminate) {
        this.delMenuForAllChild(data);
      } else {
        var num = this.selectedMenuIdList.findIndex(item => {
          return item === data.id
        })
        if (num < 0) {
          // console.log("新增一位:", data.id);
          this.selectedMenuIdList.push(data.id)
        } else {
          // console.log("原始包含id，无需新增？", data.id);
        }
        var list = this.$refs.tree.getCheckedKeys();
        list.forEach(item => {
          var num2 = this.selectedMenuIdList.findIndex(item => {
            return item === data.id
          })
          if (num2 < 0) {
            // console.log("list对比，新增一位:", item.id);
            this.selectedMenuIdList.push(item.id)
          } else {
            // console.log("list对比，原始包含id，无需新增。", item.id);
          }
        })
      }

      // //第一步先判断选择状态
      // if (checked) {
      //   this.addMenuForAllChild(data);
      //   // 向上联动
      //   // this.addMenuforAllFather(this.AllMenuIdList, data)
      // } else {
      //   //indeterminate为真时，表示改项目下面有备选择的元素，此时不做处理
      //   if (!indeterminate) {
      //     this.delMenuForAllChild(data);
      //   }

      // }
      // console.log(data, checked, indeterminate);
      //  console.log(this.$refs.tree.getCheckedKeys());
      //  console.log(  this.selectedMenuIdList);
    },

    async init() {
      this.AllMenuIdList = [];
      this.loading = true;
      var parmas = {
        seriesId: "eLabR_Middleground",
        type: 0,
        roleId: this.id
      }

      const {
        success,
        msg,
        data
      } = await GetTreeMenusByRoleTwoAsync(parmas);

      if (success) {
        this.AllMenuIdList = data;
        this.selectedMenuIdList = [];
        data.forEach(item => {
          this.changeInfo(item);
          // item.label = item.title;
          // if(item.children){
          //   item.children.forEach(itemB=>{
          //     itemB.label=itemB.title;
          //     if(itemB.children){
          //       itemB.children.forEach(itemC=>{
          //         itemC.label=itemC.title;
          //       })
          //     }
          //   })
          // }
        })
      } else {
        this.$notify.error({
          title: "失败",
          message: msg,
          duration: 3000,
        });
      }

      this.loading = false;
    },

    async save() {
      // var ids = "";
      // if (this.selectedMenuIdList.length > 0) {
      //   ids = this.selectedMenuIdList[0];
      //   for (var i = 1; i < this.selectedMenuIdList.length; i++) {
      //     ids = ids + "," + this.selectedMenuIdList[i]
      //   }
      // }
      var ids = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys()).join(',');
      const data = {
        RoleId: this.id,
        MenuIds: ids
      };
      // console.log(data);
      // return;
      const {
        success,
        msg
      } = await UpdateAuthorityAsync(data);

      if (success) {
        this.$notify({
          title: "成功",
          message: "角色权限编辑成功",
          type: "success",
          duration: 3000,
        });
        this.$router.push("/organization/role");
      } else {
        this.$notify.error({
          title: "失败",
          message: msg,
          duration: 3000,
        });
      }
    },
    // 递归函数调用
    changeInfo(item) {
      if (item.checked || item.disabled) {
        this.selectedMenuIdList.push(item.id)
      }
      item.id = item.id.toString();
      if (item.children.length > 0) {
        // console.log("有子菜单：", item.id, item.children.length);
        item.children.forEach(T => {
          this.changeInfo(T);
        })
      } else {
        // console.log("没有子菜单：", item);
        if (item.checked || item.disabled) {
          // console.log("要显示的菜单包括：", item.id);
          this.checkedMenuIdList.push(item.id)
        }
      }
    },

    // 递归函数添加确认项
    addMenuForAllChild(data) {
      var num = this.selectedMenuIdList.findIndex(item => {
        return item === data.id
      })
      if (num < 0) {
        this.selectedMenuIdList.push(data.id);
      }

      // 向下联动
      if (data.children) {
        data.children.forEach(T => {
          this.addMenuForAllChild(T);
        })
      }
    },
    // 逻辑失败
    // addMenuforAllFather(fatherList, data) {
    //   var temp =[],

    //   for (var i = 0; i < fatherList.length; i++) {
    //     var obj = null;
    //     if (fatherList[i].children.length > 0) {
    //       obj = fatherList[i].children.findIndex(child => {
    //         return child.id == data.id
    //       })
    //     }

    //     if (obj && obj > -1) {
    //       console.log("子位置：", obj, "————当前ID", data.id, "————找到的父亲对应子ID", fatherList[i].children[obj].id,
    //         "————找到的父亲：" + fatherList[i].label);
    //       this.selectedMenuIdList.push(fatherList[i].id)

    //     } else {
    //       if (i + 1 < fatherList.length) {
    //         this.addMenuforAllFather(fatherList[i + 1].children, data)
    //       }

    //     }
    //   }

    // },

    // 递归函数添加确认项
    delMenuForAllChild(data) {
      var num = this.selectedMenuIdList.findIndex(item => {
        return item === data.id
      })

      if (num > -1) {
        this.selectedMenuIdList.splice(num, 1)
      }

      if (data.children) {
        data.children.forEach(T => {
          this.delMenuForAllChild(T);
        })
      }
    },

    cancel() {
      this.$router.push("/organization/role");
    },
  },
};
</script>
<style>
  .el-col {
    border-radius: 4px;
  }

  .bg-purple-dark {
    background: #99a9bf;
  }

  .bg-purple {
    background: #d3dce6;
  }

  .bg-purple-light {
    background: #e5e9f2;
  }

  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
</style>
